/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.lswms.modules.job.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.lswms.modules.lswms.dao.task.TaskDao;
import com.lswms.modules.lswms.service.base.SequenceService;

import lombok.extern.slf4j.Slf4j;

/**
 * 扫描完成任务
 */
@Component("WMS2WCSTask")
@DisallowConcurrentExecution
@Slf4j
public class WMS2WCSTask implements ITask {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TaskDao taskDao;
//
//	@Autowired
//	private TaskRecordDao taskRecordDao;
//
//    @Autowired
//    private StockInDetailService stockInDetailService;
//
//    @Autowired
//    private StockOutService stockOutService;
//
//    @Autowired
//    private LocateService locateService;
//

	@Autowired
	private SequenceService sequenceService;

	@Autowired
	private PlatformTransactionManager txManager;

	@Override
	// @Transactional(rollbackFor = Exception.class)
	public void run(String params) {
		logger.debug("TaskTask定时任务正在执行，参数为：{}", params);

		// 读取任务表的数据,将数据发给WCS

		// 上架 读取上架库位是立体库的任务
//		 QueryWrapper<TaskEntity> wrapper = new QueryWrapper<>();
//		 wrapper.eq("status", TaskConstant.TASK_0);
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
		TransactionStatus status = null; // 获得事务状态
		try {
			List<Map<String, Object>> list = taskDao.getUndoTask();
			for (Map<String, Object> map : list) {
				try {
					status = txManager.getTransaction(def);

					Integer priority = (Integer) map.get("priority");
					String tasktype = (String) map.get("tasktype");
					String fromlocation = (String) map.get("fromlocation");
					String tolocation = (String) map.get("tolocation");
					String fromtray = (String) map.get("fromtray");
					String totray = (String) map.get("totray");
					String fromlane = (String) map.get("fromlane");
					Integer fromrow = (Integer) map.get("fromrow");
					Integer fromcolumn = (Integer) map.get("fromcolumn");
					Integer fromlevel = (Integer) map.get("fromlevel");
					String tolane = (String) map.get("tolane");
					Integer torow = (Integer) map.get("torow");
					Integer tocolumn = (Integer) map.get("tocolumn");
					Integer tolevel = (Integer) map.get("tolevel");
					String export = (String) map.get("export");

//			 /**
//				 * 任务类型:入库-PA
//				 */
//				public static final String TASK_PA = "PA";
//
//				/**
//				 * 任务类型:移库-MV
//				 */
//				public static final String TASK_MV = "MV";
//
//				/**
//				 * 任务类型:出库-PICK
//				 */
//				public static final String TASK_PICK = "PICK";
//
//				/**
//				 * 任务类型:盘点-CC
//				 */
//				public static final String TASK_CC = "CC";
//

					String wcsTaskType = ""; // 默认是移库
//			 if(tasktype.equals(TaskConstant.TASK_PA)) {
//				 wcsTaskType= "1";
//			 }else if(tasktype.equals(TaskConstant.TASK_PICK)) {
//				 wcsTaskType= "2";
//			 }

					// 只有目的巷道的是入库，只有起始巷道的出库，都没有的不发给WCS，都有的是移库
					if (StringUtils.isBlank(fromlane) && StringUtils.isNotBlank(tolane)) {
						wcsTaskType = "1";
					}
					if (StringUtils.isNotBlank(fromlane) && StringUtils.isBlank(tolane)) {
						wcsTaskType = "2";
					}
					if (StringUtils.isNotBlank(fromlane) && StringUtils.isNotBlank(tolane)) {
						wcsTaskType = "3";
					}

					if (StringUtils.isBlank(wcsTaskType)) {
						txManager.rollback(status);
						continue;
					}

					//查询是否存在重复的未完成的任务
					Integer count =taskDao.selectWCSUndoTask(fromlane);
					if(count>0) {
						txManager.rollback(status);
						continue;
					}
					
					
					// 生成新的WCS任务号
					String wcsNo = sequenceService.getSequence("WCSNO");

					// 任务号在1000~61000 之间循环
					int wcsNoInt = Integer.valueOf(wcsNo);

					int wcsNoIntSub = wcsNoInt % 31000 + 1000;

					Map<String, Object> wcsTaskMap = new HashMap<String, Object>();
					wcsTaskMap.put("task_id", wcsNoIntSub);
					wcsTaskMap.put("task_type", wcsTaskType);
					wcsTaskMap.put("task_status", 1);
					wcsTaskMap.put("priority", priority);
					wcsTaskMap.put("locate_from", fromlocation);
					wcsTaskMap.put("locate_to", tolocation);
					wcsTaskMap.put("tary_from", fromtray);
					wcsTaskMap.put("tary_to", totray);
					wcsTaskMap.put("fromlane", fromlane);
					wcsTaskMap.put("type", tasktype);
					wcsTaskMap.put("GETX", fromrow);
					wcsTaskMap.put("GETY", fromcolumn);
					wcsTaskMap.put("GETZ", fromlevel);

					wcsTaskMap.put("tolane", tolane);
					wcsTaskMap.put("PUTX", torow);
					wcsTaskMap.put("PUTY", tocolumn);
					wcsTaskMap.put("PUTZ", tolevel);
					wcsTaskMap.put("export", export);

					//校验wcs是否存在一样托盘的任务
					List<Map<String,Object>> wcstasks = taskDao.getWCSTaskRepetition(wcsTaskMap);
					System.out.println(wcstasks.size());
					if(wcstasks.size()<=0){
						// 给WCS发数据
						taskDao.sendWCS(wcsTaskMap);
					}

					// 更新WMS的任务标志
					taskDao.updateWMSTaskFlag(wcsTaskMap);
					txManager.commit(status);
				} catch (Exception e) {
					e.printStackTrace();
					txManager.rollback(status);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
